<template>
  <div class="stock-in-create">
    <el-container>
      <el-main>
        <el-card class="form-card">
          <!-- 表单头部 -->
          <template #header>
            <div class="form-header">
              <span class="title">新建入库单</span>
              <div class="actions">
                <el-button @click="handleCancel">取消</el-button>
                <el-button type="primary" @click="handleSubmit">提交</el-button>
              </div>
            </div>
          </template>

          <!-- 基本信息 -->
          <div class="section-title">基本信息</div>
          <el-form :model="formData" ref="formRef" :rules="rules" label-width="100px" class="basic-form">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="入库单号" prop="stockInCode">
                  <el-input v-model="formData.stockInCode" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="仓库" prop="warehouseId">
                  <el-select v-model="formData.warehouseId" placeholder="请选择仓库" style="width: 100%"
                    @change="handleWarehouseChange">
                    <el-option v-for="item in warehouseList" :key="item.id" :label="item.warehouseName"
                      :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="入库类型" prop="stockInType">
                  <el-select v-model="formData.stockInType" placeholder="请选择入库类型" style="width: 100%">
                    <el-option label="采购入库" value="PURCHASE" />
                    <el-option label="退货入库" value="RETURN" />
                    <el-option label="其他入库" value="OTHER" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <!-- <el-col :span="8">
                <el-form-item label="经办人" prop="operator">
                  <el-input v-model="formData.operator" />
                </el-form-item>
              </el-col> -->
              <el-col :span="8">
                <el-form-item label="入库时间" prop="stockInDate">
                  <el-date-picker v-model="formData.stockInDate" type="datetime" placeholder="选择日期时间"
                    format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                    :default-time="new Date(2000, 1, 1, 8, 0, 0)" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="formData.remark" type="textarea" :rows="2" placeholder="请输入备注信息" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <!-- 商品信息 -->
          <div class="section-title">商品信息</div>
          <div class="items-form">
            <div class="table-header">
              <el-button type="primary" @click="handleAddItem">添加商品</el-button>
            </div>

            <el-table :data="formData.items" border style="width: 100%" class="items-table">
              <el-table-column type="index" label="序号" width="55" align="center" />
              <el-table-column prop="productCode" label="商品编码">
                <template #default="scope">
                  <el-input v-model.trim="scope.row.productCode" placeholder="请输入商品编码" />
                </template>
              </el-table-column>
              <el-table-column label="商品" width="280">
                <template #default="scope">
                  <el-input v-model.trim="scope.row.productName" placeholder="请输入商品名称" />
                </template>
                <!-- <template #default="scope">
                  <el-select v-model="scope.row.productId" style="width: 100%"  filterable clearable placeholder="请输入商品编号或名称搜索"
                    @change="handleProductChange($event, scope.row)"
                    @clear="handleClearProduct(scope.row)">
                    <el-option v-for="item in productList" :key="item.id"
                                        :label="`${item.productName} - ${item.productCode} - ${item.specifications}`"
                                        :value="item.id">
                                    </el-option>
                  </el-select>
                </template> -->
              </el-table-column>
              <el-table-column label="商品图片" width="180">
                <template #default="scope">
                  <el-upload 
                    action="#" 
                    list-type="picture-card" 
                    :auto-upload="false" 
                    :limit="1" 
                    :class="{ disabled: scope.row.fileList.length>=1}"
                    :file-list="scope.row.fileList || []"
                    @change="(file, files) => checkImageFormat(file, files, scope.row)"
                  >
                    <el-icon>
                      <Plus />
                    </el-icon>
                    <template #file="{ file }">
                      <div>
                        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                        <span class="el-upload-list__item-actions">
                          <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                            <el-icon><zoom-in /></el-icon>
                          </span>
                          <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file, scope.row)">
                            <el-icon>
                              <Delete />
                            </el-icon>
                          </span>
                        </span>
                      </div>
                    </template>
                  </el-upload>
                </template>
              </el-table-column>
              <el-table-column prop="specifications" label="规格"  >
                <template #default="scope">
                  <el-input v-model.trim="scope.row.specifications" placeholder="请输入规格" />
                </template>
              </el-table-column>
              <el-table-column prop="unit" label="单位"  >
                <template #default="scope">
                  <el-input v-model.trim="scope.row.unit" placeholder="请输入单位" />
                </template>
              </el-table-column>
              <el-table-column label="数量" width="200">
                <template #default="scope">
                  <el-input-number v-model="scope.row.quantity" :min="1" @change="calculateItemAmount(scope.row)" />
                </template>
              </el-table-column>

              <el-table-column label="进价" width="200">
                <template #default="scope">
                  <el-input-number v-model="scope.row.purchasePrice" :precision="2" :step="0.1" :min="0"
                    @change="calculateItemAmount(scope.row)" />
                </template>
              </el-table-column>
              <!-- <el-table-column label="售价" width="200">
                <template #default="scope">
                  <el-input-number v-model="scope.row.sellingPrice" :precision="2" :step="0.1" :min="0"
                    @change="calculateItemAmount(scope.row)" />
                </template>
              </el-table-column> -->
              <el-table-column prop="amount" label="金额" width="150">
                <template #default="scope">
                  {{ formatAmount(scope.row.amount) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80" fixed="right">
                <template #default="scope">
                  <el-button type="danger" link @click="handleRemoveItem(scope.$index)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 合计金额 -->
            <div class="amount-summary">
              <span>合计金额：</span>
              <span class="amount">¥{{ formatAmount(totalAmount) }}</span>
            </div>
          </div>
            <!-- 图片预览 -->
  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image"  width="100%" height="100%"/>
  </el-dialog>
        </el-card>
      </el-main>
    </el-container>
  </div>

</template>

<script setup>
import { ref, reactive, computed, onMounted, toRaw } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  fetchProductList,
  fetchWarehouseList,
  createDate
} from "../../utils/commonMethods";
import { stockInApi, uploadApi } from "../../api";

const router = useRouter();

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)
// 仓库列表
const warehouseList = ref([]);
// 获取仓库列表
const getWarehouseList = async () => {
  warehouseList.value = await fetchWarehouseList();
};
// 删除图片
const handleRemove = (file, row) => {
  // 清空当前行的文件列表
  row.fileList = []
  // 清空图片相关的其他数据
  row.imageUrl = ''
  // 其他需要清理的数据...
}
// 检查图片格式
const checkImageFormat = (uploadFile, uploadFiles, row) => {
  
  // 确保每行有 fileList 数组
  if (!row.fileList) {
    row.fileList = []
  }
  row.fileList = uploadFiles.slice(-1)
  console.log('当前行:', row)
  console.log('上传的文件:', uploadFile)
}
// 图片预览
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}



// 生成入库单号
const generateStockInCode = () => {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const random = Math.floor(Math.random() * 10000)
    .toString()
    .padStart(4, "0");
  return `SI${year}${month}${day}${random}`;
};
// 初始化表单数据
const formData = reactive({
  stockInCode: generateStockInCode(),
  stockInType: "RETURN",
  warehouseId: 4,
  stockInDate: createDate(), // 格式：YYYY-MM-DD HH:mm:ss
  remark: "",
  items: [],
});

// 表单校验规则
const rules = {
  stockInType: [
    { required: true, message: "请选择入库类型", trigger: "change" },
  ],
  warehouseId: [{ required: true, message: "请选择仓库", trigger: "change" }],
  stockInDate: [
    { required: true, message: "请选择入库日期", trigger: "change" },
  ],
};

// 表单引用
const formRef = ref(null);

// 提交表单
const handleSubmit = async () => {
  if (formData.items.length === 0) {
    ElMessage.warning("请添加入库商品");
    return;
  }

  if (!formRef.value) return;

  await formRef.value.validate(async (valid) => {
    if (valid) {
      // 验证商品行
      const invalidItems = formData.items.filter((item) => !item.productCode || !item.productName || !item.specifications || !item.unit || !item.quantity || !item.purchasePrice);
      if (invalidItems.length > 0) {
        ElMessage.warning("请填写完整商品信息");
        return;
      }

      try {
        let flag = true
        for(const item of formData.items) {
            const formDataUpload = new FormData()
            // 使用 raw 属性获取原始文件对象
            const file = item.fileList[0].raw
              formDataUpload.append('file', file)
              // 上传图片
              const res = await uploadApi.upload(formDataUpload)
              if (res.code !== 200) {
                ElMessage.error('图片上传失败')
                flag = false
                return
              }
              item.imageUrl = res.data
        }
        if (!flag) return
        // 构建提交数据
        const submitData = {
          ...formData,
          totalAmount: Number(totalAmount.value.toFixed(2)),
        };
        // 调用接口保存数据
        await stockInApi.create(submitData);
        ElMessage.success("入库单创建成功");
        router.push("/stock-in/list");
      } catch (error) {
        console.error("保存失败:", error);
        ElMessage.error(error.message || "保存失败");
      }
    }
  });
};

// 取消
const handleCancel = () => {
  ElMessageBox.confirm("确认放弃当前编辑？", "提示", {
    type: "warning",
  }).then(() => {
    router.back();
  });
};

// 添加商品行
const handleAddItem = () => {
  if (!formData.warehouseId) {
    ElMessage.warning("请先选择仓库");
    return;
  }

  formData.items.push({
    // productId: "",
    productCode: "",
    productName: "",
    specifications: "",
    unit: "件",
    quantity: 1,
    purchasePrice: 0,
    amount: 0,
    imageUrl: "",
    fileList: [],
  });
};

// 删除商品行
const handleRemoveItem = (index) => {
  formData.items.splice(index, 1);
};
// 计算行金额
const calculateItemAmount = (row) => {
  if (!row.quantity || !row.purchasePrice) {
    row.amount = 0;
    return;
  }
  row.amount = Number((row.quantity * row.purchasePrice).toFixed(2));
};

// 计算总金额
const totalAmount = computed(() => {
  return formData.items.reduce((sum, item) => sum + (item.amount || 0), 0);
});

// 格式化金额
const formatAmount = (amount) => {
  return Number(amount || 0).toFixed(2);
};
// 监听仓库变化
const handleWarehouseChange = () => {
  // 清空商品列表
  formData.items = [];
};

// 初始化
onMounted(async () => {
  await getWarehouseList();
});
</script>

<style scoped>
::v-deep .disabled .el-upload--picture-card {
    display: none !important;
}
.stock-in-create {
  background-color: #f5f7fa;
  min-height: 100%;
}

.el-container {
  min-height: 100%;
}

.el-main {
  padding: 20px;
}

.form-card {
  min-height: calc(100vh - 40px);
  display: flex;
  flex-direction: column;
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.form-header .title {
  font-size: 18px;
  font-weight: bold;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin: 20px 0;
  padding-left: 10px;
  border-left: 4px solid #409eff;
}

.basic-form {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
}

.items-form {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.table-header {
  margin-bottom: 20px;
}

.items-table {
  flex: 1;
}

.amount-summary {
  margin-top: 20px;
  text-align: right;
  font-size: 16px;
}

.amount-summary .amount {
  color: #f56c6c;
  font-weight: bold;
  margin-left: 10px;
  font-size: 20px;
}
</style>